package com.flyaudio.xiaopengautopilot.view;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.flyaudio.xiaopengautopilot.R;
import com.flyaudio.xiaopengautopilot.presenter.IVehicleModule;
import com.flyaudio.xiaopengautopilot.util.AndroidDpConvert;
import com.flyaudio.xiaopengautopilot.util.BroadCastUtil;
import com.flyaudio.xiaopengautopilot.util.L;
import com.flyaudio.xiaopengautopilot.util.MySharedPreferences;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.utils.Fill;

import java.util.ArrayList;
import java.util.List;

public class MileageView implements View.OnClickListener {
    private final String TAG = "MileageView";
    public View getView() {
        return v;
    }

    private final View v;
    private Context context;

    private BarChart lineChart;
    private TextView recent_10_km, recent_100_km;

    private final int yStart = -20; //最小y值
    private final int yEnd = 80;//最大y值
    private float barWidth = 4f; //线宽
    private float xAxisMin = -100f; //最小x值
    private boolean is100km = true;

    public MileageView(Context context) {
        this.context = context;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.view_mileage, null);
        lineChart = v.findViewById(R.id.chart);
        recent_10_km = v.findViewById(R.id.recent_10_km);
        recent_100_km = v.findViewById(R.id.recent_100_km);
        recent_10_km.setOnClickListener(this);
        recent_100_km.setOnClickListener(this);
        MySharedPreferences.attachContext(context);
        update();
    }

    private void initView() {
        ArrayList<BarEntry> list;
        //设置x轴和y轴的点
        if (is100km) {
            list = IVehicleModule.getInstance().getMileageData(100,20);
        } else {
            list = IVehicleModule.getInstance().getMileageData(10,2);
        }
        L.d(TAG, "initView: " + list);
        setData(list);
        XYwangGe();
    }

    /**
     * 设置柱状图数据
     *
     * @param list
     */
    public void setData(ArrayList<BarEntry> list) {
        BarDataSet lineDataSet = new BarDataSet(list, ""); //柱状图
        setLine(lineDataSet);
        BarData data = new BarData(lineDataSet);
        if (is100km) {
            barWidth = 4.2f;
            data.setBarWidth(barWidth);
        } else {
            barWidth = 0.42f;
            data.setBarWidth(barWidth);
        }

        lineChart.setData(data);  //设置数据
        lineChart.notifyDataSetChanged();//刷新数据
        lineChart.invalidate();//重绘
    }

    private void setLine(BarDataSet set) {
        set.setAxisDependency(YAxis.AxisDependency.RIGHT);   //以右边坐标轴为基准
        //设置线条的颜色
        List<Fill> gradientFills = new ArrayList<>();
        gradientFills.add(new Fill(context.getResources().getDrawable(R.drawable.barchar_fillet_column)));

        set.setFills(gradientFills);
        set.setHighlightEnabled(false); //是否允许高亮
        set.setDrawValues(false); //是否绘制数据值
    }

    /**
     * 设置x、y坐标轴参数
     */
    private void XYwangGe() {
        XAxis xAxis = lineChart.getXAxis();
        //设置坐标间隔
        xAxis.setAxisMinimum(xAxisMin - barWidth / 2);//设置离左边位置0.5个柱状图的宽度
        xAxis.setAxisMaximum(barWidth / 2);//设置总的宽度，左右各空0.5个柱状图的宽度
        xAxis.setLabelCount(5); //设置x轴标签数，默认为6个
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                int IValue = (int) value;
                if (value == 0f) {
                    return "此刻";
                }
                return String.valueOf(IValue);
            }
        });
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM); //设置X轴标签出现位置
        xAxis.setXOffset(0);
        xAxis.setYOffset(AndroidDpConvert.px2dip(context, 32));
        xAxis.setTextSize(AndroidDpConvert.px2dip(context, 18f));
        xAxis.setTextColor(Color.parseColor("#FFFFFF"));
        xAxis.setDrawAxisLine(false); //是否绘制轴线
        xAxis.setAxisLineWidth(AndroidDpConvert.px2dip(context, 1f)); //坐标轴线的宽度
        xAxis.setAxisLineColor(Color.parseColor("#66FFFFFF")); //坐标轴线的颜色
        xAxis.setGranularityEnabled(true); //设置为true当一个页面显示条目过多，X轴值隔一个显示一个
        xAxis.setGranularity(1f); //设置最小间隔，防止当放大时，出现重复标签
        xAxis.setDrawGridLines(false);   //是否绘制网格线
//        xAxis.setEnabled(true);  //x轴是否绘制
        lineChart.getAxisLeft().setEnabled(false); //隐藏Y轴左边轴线，此时标签数字也隐藏

        YAxis yAxisR = lineChart.getAxisRight(); //右y轴
        yAxisR.setAxisMaximum(yEnd - yStart);  //设置坐标间隔
        yAxisR.setAxisMinimum(0f); //保证Y轴从0开始，不然会上移一点
        yAxisR.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                int IValue = (int) value + yStart;
                return String.valueOf(IValue);
            }
        });
        yAxisR.setDrawGridLines(false);
        yAxisR.setDrawAxisLine(false);
        yAxisR.setLabelCount(6, true);
        yAxisR.setXOffset(AndroidDpConvert.px2dip(context, 36f));
        yAxisR.setYOffset(0);
        yAxisR.setGridColor(Color.parseColor("#1FFFFFFF")); //背景表格线的颜色
        yAxisR.setGridLineWidth(AndroidDpConvert.px2dip(context, 1f)); //背景表格线的宽度
        yAxisR.setTextSize(AndroidDpConvert.px2dip(context, 18f));
        yAxisR.setTextColor(Color.parseColor("#FFFFFF"));
//        yAxisR.setEnabled(false);  //右y轴是否绘制

        // 坐标轴到边界距离  https://blog.csdn.net/feixiangsmile/article/details/75946616
        lineChart.setViewPortOffsets(33f, 36, 60f, 79f);
        lineChart.getDescription().setEnabled(false); //是否显示描述
        lineChart.setScaleEnabled(false); //是否可以缩放 x和y轴
        lineChart.setEnabled(false); //设置描述文本
        lineChart.setTouchEnabled(true); //是否可以触摸
        lineChart.setDragEnabled(true); //是否可以拖拽
        lineChart.setPinchZoom(false); //设置x轴和y轴能否同时缩放
        lineChart.setDrawBorders(false);//禁止绘制图表边框的线

        //隐藏图例
        Legend legend = lineChart.getLegend(); //获取图例对象
        legend.setEnabled(false); //设置图例不显示
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.recent_10_km:
                xAxisMin = -10f;
                is100km = false;
                setPowerComsumptionKmEnable(true);
                MySharedPreferences.setPowerComsumptionKmSwitch(true);
                BroadCastUtil.senUpdateWidgetAction(context);
                initView();
                break;
            case R.id.recent_100_km:
                xAxisMin = -100f;
                is100km = true;
                setPowerComsumptionKmEnable(false);
                MySharedPreferences.setPowerComsumptionKmSwitch(false);
                BroadCastUtil.senUpdateWidgetAction(context);
                initView();
                break;
        }
    }

    /**
     * 设置公里数值切换
     * @param isEnable
     * true 选中10km
     * false 选中100km
     */
    private void setPowerComsumptionKmEnable(boolean isEnable) {
        if(isEnable) {
            recent_10_km.setEnabled(false);
            recent_100_km.setEnabled(true);
        }else {
            recent_10_km.setEnabled(true);
            recent_100_km.setEnabled(false);
        }
    }

    public void update() {
        if (MySharedPreferences.getPowerComsumptionKmSwitch()){
            xAxisMin = -10f;
            is100km = false;
            setPowerComsumptionKmEnable(true);
        }else{
            xAxisMin = -100f;
            is100km = true;
            setPowerComsumptionKmEnable(false);
        }
        initView();
    }
}
